<template>
  <el-dialog
    title="注册"
    v-model="isRegister"
    width="400px"
    :close-on-click-modal="false"
    :before-close="handleClose"
    center
    destroy-on-close
  >
    <el-form
      :model="registerUser"
      status-icon
      :rules="rules"
      ref="ruleForm"
      label-width="0px"
      class="demo-ruleForm"
    >
      <el-form-item prop="name">
        <el-input
          v-model="registerUser.name"
          placeholder="请输入账号"
          prefix-icon="el-icon-user-solid"
        ></el-input>
      </el-form-item>
      <el-form-item prop="pass">
        <el-input
          type="password"
          v-model="registerUser.pass"
          autocomplete="off"
          placeholder="请输入密码"
          prefix-icon="el-icon-view"
        ></el-input>
      </el-form-item>
      <el-form-item prop="checkPass">
        <el-input
          type="password"
          v-model="registerUser.checkPass"
          autocomplete="off"
          placeholder="请再次输入密码"
          prefix-icon="el-icon-view"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')">注册</el-button>
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
import { defineComponent } from 'vue'
import { ElMessage } from 'element-plus'
import { findUserName, register } from '@/api'
export default defineComponent({
  name: 'RegisterPage',
  props: {
    isShow: Boolean,
  },
  data() {
    let validateName = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请输入用户名'))
      }
      // 用户名以字母开头,长度在5-16之间,允许字母数字下划线
      const userNameRule = /^[a-zA-Z][a-zA-Z0-9_]{4,15}$/
      if (userNameRule.test(value)) {
        //数据库中是否已存在
        findUserName({
          userName: this.registerUser.name,
        })
          .then((res) => {
            // “001”代表用户名不存在，可以注册
            if (res.data.code == '001') {
              this.$refs.ruleForm.validateField('name')
              return callback()
            } else {
              return callback(new Error(res.data.msg))
            }
          })
          .catch((err) => {
            return Promise.reject(err)
          })
      } else {
        return callback(new Error('字母开头,长度5-16之间,允许字母数字下划线'))
      }
    }
    let validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        // 密码以字母开头,长度在6-18之间,允许字母数字和下划线
        const passwordRule = /^[a-zA-Z]\w{5,17}$/
        if (passwordRule.test(value)) {
          this.$refs.ruleForm.validateField('checkPass')
          return callback()
        } else {
          callback(new Error('字母开头,长度6-18之间,允许字母数字和下划线'))
        }
      }
    }
    let validateCheckPass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value === this.registerUser.pass) {
        this.$refs.ruleForm.validateField('checkPass')
        return callback()
      } else {
        callback(new Error('两次输入密码不一致!'))
      }
    }
    return {
      registerUser: {
        name: '',
        pass: '',
        checkPass: '',
      },
      rules: {
        name: [{ validator: validateName, trigger: 'blur' }],
        pass: [{ validator: validatePass, trigger: 'blur' }],
        checkPass: [{ validator: validateCheckPass, trigger: 'blur' }],
      },
    }
  },
  computed: {
    isRegister: {
      get() {
        return this.isShow
      },
      set(val) {
        this.$emit('fromChild', val)
      },
    },
  },
  methods: {
    handleClose(done) {
      this.isRegister = false
      done()
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          register({
            userName: this.registerUser.name,
            password: this.registerUser.pass,
          })
            .then((res) => {
              // “001”代表注册成功，其他的均为失败
              if (res.data.code === '001') {
                // 隐藏注册组件
                this.isRegister = false
                // 弹出通知框提示注册成功信息
                // this.notifySucceed(res.data.msg);

                ElMessage.success({
                  message: '恭喜你，注册成功',
                  type: 'success',
                })
              } else {
                // 弹出通知框提示注册失败信息
                // this.notifyError(res.data.msg);
                ElMessage.error('哦，注册失败');
              }
            })
            .catch((err) => {
              return Promise.reject(err)
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
  },
})
</script>